package com.fuang.io.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.logging.Logger;

/**
 * nio2 I/O read -> handle -> write
 * <p>
 * Created by Fuang on 2018-9-20.
 */
public class TimeClientHandler extends ChannelHandlerAdapter {

    private static final Logger logger = Logger.getLogger(TimeClientHandler.class.getName());

    private int counter = 0;

    public TimeClientHandler() {
    }

    /**
     * 连接接入后，会调用此方法
     * 向服务器发送数据
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        byte[] reqByte = ("QUERY TIME ORDER" + System.getProperty("line.separator")).getBytes();
        ByteBuf req = null;
        for (int i = 0; i < 2; i++) {
            req = Unpooled.buffer(reqByte.length);
            req.writeBytes(reqByte);
            ctx.writeAndFlush(req);
        }
    }

    /**
     * 服务器发送应答时，会调用此方法读取响应内容
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 没加解码类时需要自己解码
        /*ByteBuf buf = (ByteBuf) msg;
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String body = new String(req, "UTF-8");*/
        String body = (String) msg;
        System.out.println("Now is : " + body + " ; the counter is : " + ++counter);
        ctx.disconnect();
    }

    /**
     * 异常时调用此方法
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 释放资源
        logger.warning("Unexpected exception from downstream : "
                + cause.getMessage());
        ctx.close();
    }
}
